package com.vpt;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadPoolTest {
	//H:\files\pdfs
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("Enter base directory");
		String directory = in.nextLine();
		System.out.println("Enter keyword:");
		String keyword = in.nextLine();
		
		ExecutorService pool = Executors.newCachedThreadPool();
		
		MatchCounter2 counter = new MatchCounter2(new File(directory),keyword,pool);
		Future<Integer> result=pool.submit(counter);
		
		try {
			System.out.println(result.get()+" matching files.");
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		
		pool.shutdown();
		
		int largestPoolSize = ((ThreadPoolExecutor)pool).getLargestPoolSize();
		System.out.println("largest pool size="+largestPoolSize);
		in.close();
	}
}

class MatchCounter2 implements Callable<Integer> {

	private File directory;
	private String keyword;
	private ExecutorService pool;
	private int count;

	public MatchCounter2(File directory, String keyword, ExecutorService pool) {
		this.directory = directory;
		this.keyword = keyword;
		this.pool = pool;
	}

	@Override
	public Integer call() {
		count = 0;

		File[] files = directory.listFiles();

		ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();

		for (File file : files) {
			if (file.isDirectory()) {
				MatchCounter2 counter = new MatchCounter2(file, keyword, pool);
				Future<Integer> result = pool.submit(counter);
				results.add(result);
			} else {
				if (search(file))
					count++;
			}

			for (Future<Integer> result : results) {
				try {
					count += result.get();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return count;

	}

	public boolean search(File file) {
		try {
			Scanner in = new Scanner(new FileInputStream(file));
			boolean found = false;

			while (!found && in.hasNextLine()) {
				String line = in.nextLine();
				if (line.contains(keyword))
					found = true;
			}
			in.close();
			return found;
		} catch (FileNotFoundException e) {
			return false;
		}

	}

}
